import React, { useEffect, useMemo, useState } from 'react'
import {Button} from 'antd-mobile'
import Dialog from './components/mask'
import {useSelector} from 'react-redux'
const user_id=1
const server_id=78888
const ws =new WebSocket (`ws:124.221.74.149:8003/koa/ws?user_id${user_id}&server_id=${server_id}`)
function App() {
  const [message,setMessage]=useState('')
   const [chatList,setChatList]=useState([])
  const submit=()=>{
     ws.send(
      JSON.stringify({
        type:'addMessage',
        data:{
          user_id,
          server_id,
          message
        }
      })
     )
  }

  useEffect(()=>{
    ws.addEventListener('message',res=>{
       console.log(JSON.parse(res.data))
       const {data,type}=JSON.parse(res.data)
       if(type==='getChatList'){
        setChatList(data)
       }else if(type==='addMessage'){
        setChatList((prev)=>[...prev,data])
       }
    })


    ws.addEventListener('open',()=>{
       console.log('链接成功')
       ws.send(
        JSON.stringify({
          type:'getChatList'
        })
       )
    })
  },[])
  const [show,setShow]=useState(false)
  const persons = useSelector(state=>state.person.personList)
  console.log(persons)
  
 const selcetTrue = useMemo(()=>{
  return persons.filter(item=>item.state)
 },[persons])
  return (
    <div>
      <Button block color='primary' onClick={()=>setShow(true)}>添加乘客</Button>
      <h2>乘客:</h2>
       {
         selcetTrue.map(v=>{
          return <p key={v.id}>
             {v.name}-{v.code}
          </p>
         })
       }




      {
        show&&(
            <Dialog close={()=>setShow(false)}></Dialog>
        )
      }




      <div className='chat'>
          <div className="title">
            张三
          </div>
         
          <div className="chat-list">
            {
              chatList.map((v,i)=>{
                const mm = "chat-list-" + (v.dir===1?'right':'left')
                const ll = v.dir===1 ? v.user_avatar:v.server_avatar
                return  <div className={mm} key={i}>
                 <div className="img">
              <img src={ll} alt="" />
            </div>
            <div className="content">
              <div className="text">{v.message}</div>
            </div>
            </div>
              })
            }
           

           
            
          </div>

          <div className="opration">
            <input type="text" value={message} onChange={(e)=>setMessage(e.target.value)}/>
            <button onClick={()=>submit()}>发送</button>
          </div>
      </div>
     
    </div>
  )
}

export default App
